package com.flame.system.log.service;

import java.util.List;

import com.flame.core.id.IdWorker;
import com.flame.core.utils.HttpUtils;
import com.flame.system.log.controller.vo.OperateLogSimpleVo;
import com.flame.system.log.controller.vo.OperateLogVo;
import com.flame.system.log.entity.OperateLog;
import com.flame.system.log.event.OperateCompeleteEvent;
import com.flame.system.log.mapper.OperateLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * flame_operate_log 操作日志表
 *
 * @author 吴欣童
 * @since 2023-02-24 22:22:46
 */
@Service
public class OperateLogService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OperateLogMapper operateLogMapper;

    public List<OperateLogSimpleVo> pageOperateLog(OperateLogVo operateLogVo) {
        return operateLogMapper.page(operateLogVo);
    }

    @Async
    @EventListener
    public void operateEventHandler(OperateCompeleteEvent operateCompeleteEvent) {
        OperateLog operateLog = (OperateLog) operateCompeleteEvent.getSource();
        operateLog.setLogId(idWorker.nextId());
        String[] userAgentInfo = HttpUtils.getBrowserInfoAndOperatingSystemInfo(operateCompeleteEvent.getUserAgent());
        operateLog.setBrowserInfo(userAgentInfo[0]);
        operateLog.setOperatingSystemInfo(userAgentInfo[1]);
        operateLog.setIp(operateCompeleteEvent.getIp());
        operateLog.setAddress(HttpUtils.getAddress(operateCompeleteEvent.getIp()));
        operateLogMapper.insert(operateLog);
    }

    public void batchDelete(List<Long> logIdList) {
        operateLogMapper.batchDelete(logIdList);
    }

    public void clear() {
        operateLogMapper.clear();
    }

    public OperateLog getOperateLog(Long logId) {
        return operateLogMapper.findById(logId);
    }
}
